<template>
  <div class="e-upload" :style="{ ...wrapperStyle }">
    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :limit="limit"
      v-bind="otherOptions"
      :before-upload="beforeUpload"
    >
      <slot><el-button type="primary">点击上传</el-button></slot>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

// ====== props/emit
interface IProps {
  limit?: number | string
  limitFileType?: string[]
  limitSize?: number
  otherOptions?: object
  wrapperStyle?: object
}
const props = withDefaults(defineProps<IProps>(), {
  limit: 1, // 默认每次上传文件个数
  limitFileType: () => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'], // 默认上传类型
  limitSize: 5 // 默认上传文件大小(MB)
})
const emit = defineEmits(['fileUpload'])

// ====== data
const uploadRef = ref<any>(null)

// ====== methods
const beforeUpload = (rawFile: File) => {
  if (props.limitFileType.length > 0 && !props.limitFileType.includes(rawFile.type)) {
    // 文件类型限制
    ElMessage.error('文件格式不符合')
    return false
  } else if (rawFile.size / 1024 / 1024 > props.limitSize) {
    // 文件大小限制
    ElMessage.error(`文件大小不能超过${props.limitSize}MB`)
    return false
  }

  emit('fileUpload', rawFile)
  return false
}
</script>

<style lang="less" scoped>
.e-upload {
  display: inline-block;
}
</style>
